package com.fsh.lingsp.common.common.event.listener;

import com.fsh.lingsp.common.common.event.UserRegisterEvent;
import com.fsh.lingsp.common.user.dao.UserDao;
import com.fsh.lingsp.common.user.domain.entity.User;
import com.fsh.lingsp.common.user.domain.enums.IdempotentEnum;
import com.fsh.lingsp.common.user.domain.enums.ItemEnum;
import com.fsh.lingsp.common.user.service.UserBackpackService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;

/**
 * 作者：fsh
 * 日期：2024/03/05
 * <p>
 * 描述：用户注册监听器
 */
@Component
public class UserRegisterListener {
    @Autowired
    private UserBackpackService userBackpackService;
    @Autowired
    private UserDao userDao;


    /**
     * 发放改名卡
     */
    @TransactionalEventListener(classes = UserRegisterEvent.class , phase = TransactionPhase.AFTER_COMMIT)
    public void sendRenameCard(UserRegisterEvent event){
        User user=event.getUser();
        userBackpackService.acquireItem(user.getId(), ItemEnum.MODIFY_NAME_CARD.getId(), IdempotentEnum.UID,user.getId().toString());
    }

    /**
     * 发放 徽章。   前10和前100注册的徽章
     */
    @TransactionalEventListener(classes = UserRegisterEvent.class,
            phase = TransactionPhase.AFTER_COMMIT)
    public void sendFastRegistyBadge(UserRegisterEvent event){
        User user=event.getUser();
        //统计注册人数
        int count = userDao.count();
        if(count<=10){
            //发放前10徽章
            userBackpackService.acquireItem(user.getId(),
                    ItemEnum.REG_TOP10_BADGE.getId(),
                    IdempotentEnum.UID,
                    user.getId().toString());
        }else if(count<=100){
            //发放前100徽章
            userBackpackService.acquireItem(user.getId(),
                    ItemEnum.REG_TOP100_BADGE.getId(),
                    IdempotentEnum.UID,
                    user.getId().toString());
        }
    }



}
